//
//  SYJHomeViewController.swift
//  weibo
//
//  Created by 孙英建 on 16/4/16.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

// 可重用标示符
private let key = "cell"
class SYJHomeViewController: SYJVisitorViewController {

    
    // 保存微博数据数组
    var statusArr: [SYJStatusesModel] = [SYJStatusesModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 判断我们用户是否登录
        if !isLogin{
            visitorView?.setVisitorInfo(nil, titleName: nil)
            return
        }
        
        // 设置下拉刷新显示微博条数的文字
        navigationController!.view.insertSubview(messageLabel, belowSubview: navigationController!.navigationBar)
        
        messageLabel.frame = CGRect(x: 0, y: 64 - 34, width: kWidth, height: 34)
       
        
        // 注册cell
        tableView.registerClass(SYJHomeCell.self, forCellReuseIdentifier: key)
        
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 300
        
        tableView.separatorStyle = .None
        
        // 添加刷新控件
        tableView.tableFooterView = indicatorView
        
        // 下拉刷新
        tableView.addSubview(refresh)
        
        refresh.addTarget(self, action: "refreshAction", forControlEvents: UIControlEvents.ValueChanged)
        
        // 加载数据
        loadData(indicatorView.isAnimating())
    }
    
    // 下拉刷新
    func refreshAction(){
        loadData(indicatorView.isAnimating())
    }
    
    // MARK: - 懒加载控件
    private lazy var indicatorView: UIActivityIndicatorView = {
       let iv = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        iv.color = UIColor.orangeColor()
        return iv
    }()
    
    // 下拉刷新小菊花
    private lazy var refresh:SYJRefreshControl = SYJRefreshControl()
    
    // 显示加载了多少条微博的label
    private lazy var messageLabel: UILabel = {
       let ml = UILabel()
        ml.textColor = UIColor.whiteColor()
        ml.font = UIFont.systemFontOfSize(14)
        ml.backgroundColor = UIColor.orangeColor()
        ml.textAlignment = NSTextAlignment.Center
        ml.text = "显示微博条数的文字"
        ml.hidden = true
        return ml
    }()
}

// MARK: - 数据源方法和代理方法
extension SYJHomeViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusArr.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(key, forIndexPath: indexPath) as! SYJHomeCell
        
        cell.statusesModel = statusArr[indexPath.row]
        
        cell.tabarView.buttonClickClosure = {[weak self] (tag: Int) in
            switch tag {
            case 3001:
                print("转发")
            case 3002:
                print("评论")
            case 3003:
                print("赞")
            default:
                break
            }
        }
        
        return cell
    }
    
    // 监听cell滚动的位置
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.row == self.statusArr.count - 1 && !indicatorView.isAnimating(){
            indicatorView.startAnimating()
            loadData(indicatorView.isAnimating())
        }
    }
    
}


extension SYJHomeViewController{
    
    // MARK: - 数据请求
    func loadData(isPullUP: Bool){
        
        var since_id: Int64 = 0
        var max_id: Int64 = 0
        
        // 判断是下拉刷新还是上拉加载更多
        if isPullUP{
            // 上拉加载更多
            since_id = 0
            max_id = self.statusArr.last?.id ?? 0

            if max_id > 0 {
                max_id -= 1
            }
            
        }else{
            // 下拉刷新
            since_id = self.statusArr.first?.id ?? 0
            max_id = 0
            
        }

        SYJStatusDAL.getHomeStatus(since_id, max_id: max_id) { (array) -> () in
            
            // 停止动画
            self.indicatorView.stopAnimating()
            self.refresh.endRefreshing()
            
            if array.count == 0 {
                
                return
            }
            
            // 转模型
            var tempArr: [SYJStatusesModel] = [SYJStatusesModel]()
            
            for dict in array {
                let status = SYJStatusesModel(dict: dict)
                tempArr.append(status)
            }
            
            if isPullUP{
                self.statusArr = self.statusArr + tempArr
                
            }else{
                self.statusArr = tempArr + self.statusArr
                // 如果处在隐藏状态则执行动画
                if self.messageLabel.hidden == true{
                    self.setMessageLabelAnimate(tempArr.count)
                }
            }
            
            self.tableView.reloadData()
            
        }
            
        
        
        
    }
    
    // MARK: -显示微博条数文字的动画
    func setMessageLabelAnimate(count: Int){
        messageLabel.hidden = false
        
        var countStr: String?
        
        if count == 0 {
            countStr = "已经是最新微博了"
        }else{
            countStr = "您更新了\(count)条微博"
        }
        
        messageLabel.text = countStr
        
        // 设置提示文字的显示和隐藏
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.messageLabel.frame.origin.y = 64
            }) { (_) -> Void in
                UIView.animateWithDuration(1, delay: 1, options: [], animations: { () -> Void in
                    self.messageLabel.frame.origin.y = 64 - 34
                    }, completion: { (_) -> Void in
                        self.messageLabel.hidden = true
                })
        }
        
    }
    
    
}











